using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
using System.Xml.Serialization;
using System.Xml.Schema;
using CSF.Communications.Sdp.ServiceLogic.Exceptions;
using CSF.Communications.Sdp.ServiceLogic.DataAccess;
using Microsoft.ApplicationBlocks.ExceptionManagement;
using CSF.Communications.Sdp.ServiceLogic.Entities;
using System.Data;
using System.Collections.Specialized;

namespace CSF.Communications.Sdp.ServiceLogic.Utilities
{
    public class MapServiceProvider
    {
        public MapServiceProvider()
        {
            
        }

        #region GetDynamicXML
        /// <summary>
        /// 
        /// </summary>
        /// <param name="serviceName"></param>
        /// <param name="paramaters"></param>
        /// <param name="strInputXml"></param>
        /// <returns></returns>
        public string GetDynamicXML(String map, string strInputXml)
        {
            StringWriter oSW = new StringWriter();
            try
            {
                XmlDocument doc = new XmlDocument();
              //  DataAccess.DataServiceProvider dsp = new BT.Communications.Sdp.ServiceLogic.DataAccess.DataServiceProvider();

               // string strMap = dsp.GetDynamicMapfromDatabase(mapName);
                string strMap = map;

                strMap = strMap.Replace("''", "'");

                // string strMap = Resources.Resource.ResourceManager.GetString(mapName);
                doc.LoadXml(strMap);

                StringReader strReader = new StringReader(strMap);
                XmlTextReader reader = new XmlTextReader(strReader);

                StringReader strSourceReader = new StringReader(strInputXml);
                XmlTextReader sourceReader = new XmlTextReader(strSourceReader);

                XPathDocument xPath = new XPathDocument(sourceReader);
                XslCompiledTransform ioMap = new XslCompiledTransform();

                ioMap.Load(reader);
                ioMap.Transform(xPath, null, oSW);
            }
            catch (Exception ex)
            {
                throw new SDPSystemException(Convert.ToInt64(SDPSystemError.SDPDynamicMapTrnsformationException), ex.Message);
            }
            return oSW.ToString();
        }
        #endregion

        #region GetServiceOutputXML
        /// <summary>
        /// 
        /// </summary>
        /// <param name="serviceName"></param>
        /// <param name="paramaters"></param>
        /// <param name="strInputXml"></param>
        /// <returns></returns>
        public string GetServiceOutputXML(String serviceUUID, string action, string strInputXml)
        {
            StringWriter oSW = new StringWriter();
            try
            {
                XmlDocument doc = new XmlDocument();
                DataAccess.DataServiceProvider dsp = new CSF.Communications.Sdp.ServiceLogic.DataAccess.DataServiceProvider();

                string strMap = dsp.GetIOMapfromDatabase(serviceUUID, action);

                doc.LoadXml(strMap);

                StringReader strReader = new StringReader(strMap);
                XmlTextReader reader = new XmlTextReader(strReader);

                StringReader strSourceReader = new StringReader(strInputXml);
                XmlTextReader sourceReader = new XmlTextReader(strSourceReader);

                XPathDocument xPath = new XPathDocument(sourceReader);
                XslCompiledTransform ioMap = new XslCompiledTransform();

                ioMap.Load(reader);
                ioMap.Transform(xPath, null, oSW);
                return oSW.ToString();
            }

            catch (ApplicationException appEx)
            {
                throw appEx;             
            }
            catch (Exception ex)
            {
                ExceptionManager.Publish(ex, Convert.ToInt32(SDPSystemError.SDPIOMAPTrnsformationException));                   
                throw new ApplicationException(ex.Message);
            }
            
        }
        #endregion

        #region GetSimpleDynamicMap
        /// <summary>
        /// 
        /// </summary>
        /// <param name="map"></param>
        /// <param name="strInputXml"></param>
        /// <returns></returns>
        public CSF_MID GetSimpleDynamicMap(String map, CSF_MID mid, DataSet ds)
        {
            StringCollection fromServColl = null;
            Service[] fromService = null;
            NameValueCollection fromServicenvc = null;
            Service toService= null;
            NameValueCollection isServiceCounted = null;
         
            try
            {
                if (ds != null && ds.Tables != null && ds.Tables.Count > 0 && ds.Tables[0] != null && ds.Tables[0].Rows != null && ds.Tables[0].Rows.Count > 0)
                {

                    toService = new Service();
                    fromServicenvc = new NameValueCollection();
                    toService.inputcharacteristics = new string[ds.Tables[0].Rows.Count];
                    fromServColl = new StringCollection();
                    isServiceCounted = new NameValueCollection();
                    int fromcharCount = 0;

                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        if (fromServicenvc[row[1].ToString()] == null)
                        {
                            fromServicenvc.Add(row[1].ToString(), "1");
                        }
                        else
                        {
                            fromcharCount = Convert.ToInt32(fromServicenvc[row[1].ToString()]);
                            fromcharCount++;
                            fromServicenvc[row[1].ToString()] = fromcharCount.ToString();
                        }

                        if (!fromServColl.Contains(row[1].ToString()))
                        {
                            fromServColl.Add(row[1].ToString());
                        }
                    }

                    if (fromServColl.Count > 0)
                    {
                        fromService = new Service[fromServColl.Count];
                    }

                    int fromServCount = 0;
                    foreach (String str in fromServColl)
                    {
                        fromService[fromServCount] = new Service();
                        fromService[fromServCount].vasId = str;
                        fromServCount++;
                    }

                    int toServCharacCount = 0;
                    fromServCount = 0;

                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        if (toService.vasId == null)
                        {
                            toService.vasId = row[2].ToString();
                        }
                        toService.inputcharacteristics[toServCharacCount] = row[3].ToString();
                        toServCharacCount++;

                        if (isServiceCounted[row[1].ToString()] == null)
                        {
                            isServiceCounted.Add(row[1].ToString(), row[1].ToString());

                            fromService[fromServCount].outputcharacteristics = new String[Convert.ToInt32(fromServicenvc[fromService[fromServCount].vasId])];

                            int charCount = 0;
                            foreach (DataRow dr in ds.Tables[0].Rows)
                            {
                                if (dr[1].ToString() == fromService[fromServCount].vasId)
                                {
                                    fromService[fromServCount].outputcharacteristics[charCount] = dr[0].ToString();
                                }

                                charCount++;
                            }
                            fromServCount++;
                        }
                    }

                    foreach (ServiceLogicPayloadTypeVASData vasdata in mid.VASDataCollection)
                    {

                        if (vasdata.VASID == toService.vasId)
                        {
                            toService.vasdata = vasdata;
                            toService.vasdataXml = new XmlDocument();
                            toService.vasdataXml.LoadXml(vasdata.SerializeObject());

                        }
                        foreach (Service serv in fromService)
                        {
                            if (vasdata.VASID == serv.vasId)
                            {
                                serv.vasdata = vasdata;
                                serv.vasdataXml = new XmlDocument();
                                serv.vasdataXml.LoadXml(vasdata.SerializeObject());

                            }
                        }
                    }

                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        string fromCharValue = null;
                        XmlNodeList nl;
                        foreach (Service serv in fromService)
                        {
                            if (serv.vasId == row[1].ToString())
                            {
                                nl = serv.vasdataXml.GetElementsByTagName(row[0].ToString());
                                if (nl != null)
                                {
                                    if (nl[0] != null)
                                    {
                                        fromCharValue = nl[0].InnerXml;
                                    }
                                }

                                nl = toService.vasdataXml.GetElementsByTagName(row[3].ToString());
                                if (fromCharValue != null && fromCharValue != String.Empty)
                                {
                                    if (nl != null)
                                    {
                                        if (nl[0] != null)
                                        {
                                            nl[0].InnerXml = fromCharValue;
                                        }
                                    }
                                }
                            }
                        }

                        
                    }

                    foreach (ServiceLogicPayloadTypeVASData vasdata_mid in mid.VASDataCollection)
                    {
                        if (vasdata_mid.VASID == toService.vasId)
                        {
                            vasdata_mid.VasRequest = vasdata_mid.DeSerializeObject(toService.vasdataXml.InnerXml).VasRequest;
                            break;
                        }
                    }
                }
                else
                {
                    //  throw new Exception(

                }

                return mid;
            }
            catch (Exception ex)
            {
                ExceptionManager.Publish(ex, Convert.ToInt32(SDPSystemError.SDPIOMAPTrnsformationException));
                throw new ApplicationException(ex.Message);
            }
        }

        #endregion
    }
}
